<?php

namespace App\Models;

use App\ModelFilters\Qh_QuestionFilter;
use App\Service\Redis\RedisBaseService;
use Auth;
use DB;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Qh_Question extends BaseModel
{
    protected $table = 'qh_questions';

    protected $guarded = [];

    //protected $appends = ['userResult', 'userAnswer', 'questionTypeName', 'knowledgeName', 'userQuestionRate', 'isCollect', 'courseName', 'questionLibraryName'];
    protected $appends = ['userResult', 'userAnswer', 'questionTypeName', 'userQuestionRate', 'isCollect'];

    /**
     * 用户的答题结果
     * @return bool|mixed|null
     * @throws \RedisException
     */
    public function getUserResultAttribute()
    {
        $result = null;

        if (request()->is('api/qh_mp/getQuestionsByKnowledge')) return null;

        if (Auth::guard('api')->check()) {
            $user = Auth::guard('api')->user();
            if (request()->route()->uri == 'api/qh_mp/getKaoshiResult/{id}') {
                // $result = DB::table('qh_user_kaoshi_question_logs')->where('userId', $user->id)->where('questionId', $this->id)->value('result');
                $result = (new RedisBaseService())->getUserLearnQuestionLog($user->id, $this->id, 2);
            }else {
                $result = (new RedisBaseService())->getUserLearnQuestionLog($user->id, $this->id, 1);
                // $result = DB::table('qh_user_question_logs')->where('userId', $user->id)->where('questionId', $this->id)->value('result');
            }
        }
        return $result ? $result['result'] : null;
    }

    /**
     * 判断用户是否收藏了
     * @return bool
     * @throws \RedisException
     */
    public function getIsCollectAttribute(): bool
    {
        if (request()->is('api/qh_mp/getQuestionsByKnowledge')) return false;

        $collect = false;

        if (Auth::guard('api')->check()) {
            $user = Auth::guard('api')->user();
            $ids = (new RedisBaseService())->getUserWrongOrCollectQuestionStructureData($user->id, 2);
            $collect = !empty(getLevelDataFromWrongOrCollectQuestionStructureData($ids, 4, $this->id));
            // $collect = (bool)Qh_UserCollectQuestion::where('userId', $user->id)->where('questionId', $this->id)->first();
        }
        return $collect;
    }

    /**
     * 用户的答案
     * @return mixed|null
     * @throws \RedisException
     */
    public function getUserAnswerAttribute() {
        if (request()->is('api/qh_mp/getQuestionsByKnowledge')) return null;

        $answer = null;
        if (Auth::guard('api')->check()) {
            $user = Auth::guard('api')->user();
            if (request()->route()->uri == 'api/qh_mp/getKaoshiResult/{id}' || request()->route()->uri == 'api/qh_mp/getQuestionsByIds') {
                // $answer = DB::table('qh_user_kaoshi_question_logs')->where('userId', $user->id)->where('questionId', $this->id)->value('userAnswer');
                $result = (new RedisBaseService())->getUserLearnQuestionLog($user->id, $this->id);
                $answer = isset($result) ? $result['userAnswer'] : null;
            }else {
                $answer = DB::table('qh_user_question_logs')->where('userId', $user->id)->where('questionId', $this->id)->value('userAnswer');
            }
        }
        return $answer;
    }

    /**
     * 用户答题正确率
     */
    public function getUserQuestionRateAttribute(): float
    {
        if (request()->is('api/qh_mp/getQuestionsByKnowledge')) return 0;

        $rate = 0;
        $sum = $this->rightCount+$this->wrongCount;
        if ($sum > 0) {
            $rate = round(($this->rightCount / $sum) * 100, 2);
        }
        return $rate;
    }

    /**
     * options
     * @param $v
     * @return array
     */
    public function getOptionsAttribute($v)
    {
        if (request()->is('admin/*')) return $v;

        if (empty($v)) return [];

        $options = explode('|NTK|', $v);
        $optionList = [];
        foreach ($options as $o) {
            if(empty($o)) continue;
            $_o = explode('、',$o, 2);
            if (empty($_o) || count($_o) < 2) {
                $_o_e = mb_substr($o, 1, 1, 'UTF-8');
                if ($_o_e == '.') {
                    $_o = explode('.',$o, 2);
                }else {
                    $compare_str = mb_convert_kana($_o_e, 'R', 'UTF-8'); // 将半角句号转换为全角句号
                    if ($_o_e == $compare_str) {
                        $_o = explode('．',$o, 2);
                    };
                }
            }

            if(empty($_o) || count($_o) < 2) continue;
            $optionList[] = [
                'key' => trim(strip_tags($_o[0])),
                'value' => replaceStaticFileUrlInString($_o[1]),
            ];
        }

        return $optionList;
    }

    /**
     * 获取题型名称
     * @return mixed|null
     */
    public function getQuestionTypeNameAttribute() {
        if (request()->is('api/qh_mp/getQuestionsByKnowledge')) return null;

        return Qh_QuestionType::where('id', $this->questionTypeId)->value('name');
    }

    //public function getQuestionLibraryNameAttribute() {
    //    return Qh_QuestionLibrary::where('id', $this->qlId)->value('name');
    //}
    //
    //public function getCourseNameAttribute() {
    //    return Qh_Course::where('id', $this->courseId)->value('name');
    //}
    //
    //public function getKnowledgeNameAttribute() {
    //    return Qh_Knowledge::where('id', $this->knowledgeId)->value('name');
    //}

    public function modelFilter(): ?string
    {
        return $this->provideFilter(Qh_QuestionFilter::class);
    }

    public function questionLibrary(): BelongsTo
    {
        return $this->belongsTo(Qh_QuestionLibrary::class, 'qlId');
    }

    public function course(): BelongsTo
    {
        return $this->belongsTo(Qh_Course::class, 'courseId');
    }

    public function knowledge(): BelongsTo
    {
        return $this->belongsTo(Qh_Knowledge::class, 'knowledgeId');
    }

    public function children(): HasMany
    {
        return $this->hasMany(Qh_LitQuestion::class, 'parentId');
    }

    public function getTitleAttribute($v) {
        return replaceStaticFileUrlInString($v);
    }

    public function getAnswerAttribute($v) {
        if ($this->questionTypeId == 100 ||
            $this->questionTypeId == 1 ||
            $this->questionTypeId == 2 ||
            $this->questionTypeId == 3 ||
            $this->questionTypeId == 7) return trim(strip_tags($v));
        return replaceStaticFileUrlInString($v);
    }

    public function getAnalysisAttribute($v) {
        return replaceStaticFileUrlInString($v);
    }
}
